import { BASE_URL, DEFAULT_TIMEOUT_MS, DEFAULT_HEADERS } from './config.js'

function buildUrl(path) {
  if (path.startsWith('http')) return path
  return `${BASE_URL}${path}`
}

function getAuthHeader() {
  // [接口位置] 鉴权：如需 token，请在此读取并加入请求头
  const token = uni.getStorageSync('token') || ''
  return token ? { Authorization: `Bearer ${token}` } : {}
}

export function request({ url, method = 'GET', data = {}, header = {}, timeout = DEFAULT_TIMEOUT_MS }) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: buildUrl(url),
      method,
      data,
      header: { ...DEFAULT_HEADERS, ...getAuthHeader(), ...header },
      timeout,
      success: (res) => {
        // [接口位置] 统一错误处理（可按项目约定调整）
        const { statusCode, data } = res
        if (statusCode >= 200 && statusCode < 300) {
          resolve(res)
        } else {
          // 将服务端错误透出
          const message = (data && (data.message || data.msg)) || `请求失败(${statusCode})`
          console.warn('Request error:', message, url)
          uni.showToast({ title: message, icon: 'none' })
          resolve(res)
        }
      },
      fail: (err) => {
        // 网络层错误统一提示（开发模式更温和，避免频繁打断）
        console.warn('Network error:', err && err.errMsg)
        uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' })
        reject(err)
      }
    })
  })
}

export async function get(path, params = {}, header = {}) {
  return request({ url: path, method: 'GET', data: params, header })
}

export async function post(path, body = {}, header = {}) {
  return request({ url: path, method: 'POST', data: body, header })
}


